package com.controler;
import com.domain.Page;
import com.domain.myfile;
import com.service.myfileService;
import com.sun.deploy.net.HttpResponse;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/filepost")
public class FileController {
@Autowired
private myfileService  myfile;
@RequestMapping("/fileUpload")
public ModelAndView fileUpload(HttpServletRequest request, MultipartFile upload, String namew, String type) throws IOException {
    ModelAndView mv = new ModelAndView();
    String path=request.getSession().getServletContext().getRealPath("/uploads/"); //将文件上床到服务器的这个路径
    System.out.println(path);
    File file=new File(path);
    if(!(file.exists()))
    {
        //文件夹不存在就创建这个文件夹
        file.mkdirs();
    }
    String name=upload.getOriginalFilename();//获取文件的名字
    String suffix = name.substring(name.lastIndexOf(".")+1); //获取文件的后缀
    if(!suffix.equals(type))
    {
        mv.setViewName("cons2");
        return mv;
    }
    File[] files = (new File(path)).listFiles();
    for (File file2 : files) {
        System.out.println(file2);
    }
    File file1=new File(path+"\\name");
    Instant instant= Files.readAttributes(Paths.get(path), BasicFileAttributes.class).creationTime().toInstant();
    String format = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss").withZone(ZoneId.systemDefault()).format(instant);
    mv.addObject("files",files);
    myfile  a=new myfile();
    a=myfile.findfileByfilename(name);
    System.out.println(a);
    if(a==null)   //没有这个文件
    {
        myfile b=new myfile(name,namew,0,suffix,(path+name),format);
        myfile.inservalueintotable(b);
    }
    else
    {
        mv.setViewName("tests");
        return mv;
    }
    String uuid= UUID.randomUUID().toString().replace("-","");
    upload.transferTo(new File(path,name));
    mv.setViewName("redirect:/filepost/findpage?start=0");
    return mv;
}
    @RequestMapping("/search")
    public ModelAndView serchfileBytype(String akd) throws SQLException {
        ModelAndView mv = new ModelAndView();
        List<myfile> myfiles=myfile.findfileBytype(akd);
        mv.addObject("array",myfiles);
        mv.setViewName("cons3");
        return mv;
    }
    @RequestMapping("/download")
    public void Filedownload(String filename, HttpServletRequest res, HttpServletResponse rep, int fixtimes) throws IOException, SQLException {
        //下载是2进制的响应输出，必须设置响应头信息
        rep.setHeader("Content-Disposition", "attachment;filename="+filename);
        //创建输出流 二进制
        ServletOutputStream os = rep.getOutputStream();
        //根据提供fileName，定位下载的文件
        //确定的下载文件的绝对路径
        String path = res.getSession().getServletContext().getRealPath("uploads");
        System.out.println("下载路径"+path);
        File file = new File(path, filename);
        myfile.updateFileloadtimeByfilename(++fixtimes,filename);
        byte[] bytes = FileUtils.readFileToByteArray(file);
        os.write(bytes);
        os.flush();
        os.close();
    }

    @RequestMapping("/findpage")
    public ModelAndView findpage(int start)
    {
        ModelAndView modelView = new ModelAndView();
        int count = 3; //每页显示的条目数
        Page page = new Page(start,count); //将得到的值存入page对象中
        //从数据库中取值 将 start 和count 传入
        // 后台sql语句如下：
        // SELECT * FROM user LIMIT #{start}, #{和count}
        //第一个参数是开始数据的索引位置
        //第二个参数是要查询多少条数据
        //这里解释一下原理，每次从数据库中取出部分数据，可防止内存溢出
        List<myfile> myfileList = myfile.findBypage(page.getStart(),page.getCount());  //获取用户list

        // 后台sql语句如下
        // SELECT COUNT(*) FROM user
        //获取user表中用户总个数
        int total = myfile.selectCount();
        page.setTotal(total);//设置page对象的总数据量
        System.out.println(myfileList);
        //通过addObject存储page和用户list
        modelView.addObject("page", page);
        modelView.addObject("userList", myfileList);
        //利用setViewName设定跳转页面
        modelView.setViewName("sucess");
        //返回ModelAndView对象 跳转
        return modelView;
    }
}

